#include "StdAfx.h"
#include "NetCfg.h"
#include "3rdSDK/netadapter.h"

CNetCfg::CNetCfg(void)
: m_pAdapters(NULL)
, m_nCount(0)
{
	BuildAdapterListing();
}

CNetCfg::~CNetCfg(void)
{
	if(m_pAdapters)
		delete [] m_pAdapters;
}

BOOL CNetCfg::BuildAdapterListing()
{
	BOOL	bRet		= TRUE;
	DWORD	dwErr		= 0;
	ULONG	ulNeeded	= 0;

	dwErr = EnumNetworkAdapters( m_pAdapters, 0, &ulNeeded );

	if( dwErr == ERROR_INSUFFICIENT_BUFFER ) {		
		m_nCount	= ulNeeded / sizeof( CNetworkAdapter );
		m_pAdapters = new CNetworkAdapter[ ulNeeded / sizeof( CNetworkAdapter ) ];		
		dwErr		= EnumNetworkAdapters( m_pAdapters, ulNeeded, &ulNeeded );		
		if( ! m_pAdapters ) {
			AfxMessageBox( _T("No Network Adapters Found on System."), MB_OK | MB_ICONERROR );
			bRet = FALSE;
		}		
	}else{
		AfxMessageBox( _T("No Network Adapters Found on System."), MB_OK | MB_ICONERROR );
		bRet = FALSE;
	}
	return bRet;
}

void CNetCfg::ListAdapterInfo()
{
	CString sType,
		sIP,
		sDesc,
		sSub,
		sGate,
		sDns1,
		sDns2;

	CNetworkAdapter* pAdapt = NULL;

	if( m_pAdapters ) {			
		for(int m_nDisplay=0; m_nDisplay<m_nCount; ++m_nDisplay) {
			ListAdapterInfo( &m_pAdapters[ m_nDisplay ] );
		}
	}				
}

void CNetCfg::ListAdapterInfo( CNetworkAdapter* pAdapt )
{
	CString sType;
	CString sIP;
	CString sDesc;
	CString sSub;
	CString sGate;
	CString sDns1;
	CString sDns2;

	( pAdapt->IsDhcpUsed() ) ? sType = _T("Dynamic Address (DHCP)") : sType = _T("Static IP");

	sIP = pAdapt->GetIpAddr().c_str();
	sDesc = pAdapt->GetAdapterDescription().c_str();
	sSub = pAdapt->GetSubnetForIpAddr().c_str();
	sGate = pAdapt->GetGatewayAddr().c_str();
	sDns1 = pAdapt->GetDnsAddr( 0 ).c_str();
	sDns2 = pAdapt->GetDnsAddr( 1 ).c_str();

	printf("[ %s ]\n",sDesc);
	printf("Address Type    = %s\n",sType);
	printf("Network Address = %s\n",sIP);
	printf("Subnet Mask     = %s\n",sSub);
	printf("Default Gateway = %s\n",sGate);
	printf("Primary DNS     = %s\n",sDns1);
	printf("Seconary DNS    = %s\n",sDns2);
	printf("\n");
}